import { observable, action, runInAction } from 'mobx';
import { message } from 'antd';
import type { DataType } from './config/interface';
import {
  getTableDataList,
  addTableDataList,
  editTableDataItem,
  delTableDataItem
} from '@/api/archives/practice';

function insertItem(data: DataType, list: any[], originLength: number) {
  list.unshift(data);
  if (list.length >= originLength) list.pop();
  return list.map((item: DataType) => item);
}

const state = observable({
  payload: {
    pageNo: 1,
    pageSize: 5,
    param: { businessType: 1, receiveType: 1 }
  },
  total: 0,
  tableList: [],
  loading: true
});

const actions = {
  queryTableList: action(async () => {
    state.loading = true;
    const { data } = await getTableDataList(state.payload);
    runInAction(() => {
      state.tableList = data.results;
      state.total = data.totalCount;
      state.loading = false;
    });
  }),
  pageChange: (page: number) => {
    state.payload.pageNo = page;
    actions.queryTableList();
  },
  submit: action(async (form: DataType) => {
    if (form.id) {
      await editTableDataItem(form);
      message.success('编辑成功');
      actions.queryTableList();
    } else {
      const { data } = await addTableDataList({ ...form, fondsId: 5, archiveTypeId: 16 });
      message.success('新建成功');
      runInAction(() => {
        state.tableList = insertItem(data, state.tableList, state.payload.pageSize);
      });
    }
  }),
  delTableItem: action(async (id: number) => {
    await delTableDataItem(id);
    message.success('已删除');
    actions.queryTableList();
  })
};

export { state, actions };
